<template>
    <div>
<!--        <el-button @click="testb">test button</el-button>-->
        <el-tabs v-model="activeTab" type="card" @tab-remove="removeTab" @tab-click="tabClick">
            <el-tab-pane v-for="(item, index) in tabsItem"
                         :key="item.chat_id"
                         :label="item.title"
                         :name="item.chat_id"
                         :ref="item.ref"
                         class="word"
            >
                <component :is="item.content"
                           v-bind:chat_id='item.chat_id'
                           v-bind:chat_data="chat_data"
                           v-bind:c_name="item.title"
                           v-bind:level="level"
                           @sendMes="sendMes">
                </component>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import ChatRoom from '@/components/page/ChatRoom';
import axios from 'axios';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

export default {
    name: 'Home',
    props: ['room_info','level','authority'],
    data() {
        return {
            stompClient: null,
            isCollapse: false,  //false为展开 true为收缩
            socket: null,
            activeTab: '1', //默认显示的tab
            tabIndex: 2, //tab目前显示数
            header:"Bearer "+localStorage.getItem('token'),
            chat_data: [
            ],
            tabsItem: [
                {
                    title: '首页',
                    chat_id: 0,
                    closable: false,
                    ref: 'tabs',
                    content: ChatRoom
                },
                {
                    title: '测试对话1',
                    chat_id: 1,
                    closable: true,
                    ref: 'tabs',
                    content: ChatRoom
                }
            ],
            tabsPath: [
                {
                    chat_id: 0,
                    path: '/chatroom',
                    path_name: 'chatroom'
                },
                {
                    chat_id: 1,
                    path: '/chatroom',
                    path_name: 'chatroom'
                }
            ]
        };
    },
    computed: {
        setHeight() {
            return document.documentElement.clientHeight - 65;
        }
    },
    watch: {
        '$route'(to, from) {
            this.$router.go(0);
        }
    },
    methods: {
        testb() {
            this.chat_data.push();
        },
        getMes(mes){
            if(this.tabsItem.find(item => item.chat_id === mes.chat_id)===false){
                axios.post(
                    axios.defaults.baseURL + 'room/getChatGroup',
                    { chatId:mes.chat_id }
                ).then((res) => {
                    if(res.data.code==="000000"){
                        console.log("接收新的chat group");
                        if(res.data.content.rid===this.room_info.rid){
                            this.$message.success("出现新的chat group");
                            let add_tabItem={
                                title: mes.data.title,
                                chat_id: mes.data.chat_id,
                                closable: false,
                                ref: 'tabs',
                                content: ChatRoom
                            };
                            let add_tabsPath={
                                chat_id: mes.chat_id,
                                path: '/chatroom',
                                path_name: 'chatroom'
                            };
                            this.tabsItem.push(add_tabItem);
                            this.tabsPath.push(add_tabsPath);
                        }
                    }else{
                        this.$message.error(res.data.desc)
                    }
                })
                this.tabsItem.push()
            }
        },
        getTime() {
            //获取当前时间并打印
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth() + 1;
            let dd = new Date().getDate();
            let hh = new Date().getHours();
            let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
            let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
            return yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss;
        },
        initWebSocket() {
            this.connection();
            // let that = this;
            // // 断开重连机制,尝试发送消息,捕获异常发生时重连
            // this.timer = setInterval(() => {
            //   try {
            //     that.stompClient.send("/app/test",
            //         this.headers,
            //         JSON.stringify({'senderuid': 7, 'content': 'aaaa'}),
            //     )
            //   } catch (err) {
            //     console.log("断线了: " + err);
            //     that.connection();
            //   }
            // }, 5000);
        },
        sendMes(mes) {
            console.log('父组件发送!');
            this.stompClient.send('/app/send', this.headers, JSON.stringify({
                uid: localStorage.getItem('uid'),
                name: localStorage.getItem('nickname'),
                chat_id: mes.chat_id,
                cid:-1,
                content: mes.content,
                time: this.getTime()
            }));
        },
        addData(mes){
            this.chat_data.push(mes);
        },
        connection() {
            let that=this;
            // 建立连接对象
            this.socket = new SockJS('http://localhost:8081/chatRoom//?Authorization=Bearer ' + localStorage.getItem('token'));
            // this.socket = new SockJS("http://localhost:8081/chatRoom");
            // 获取STOMP子协议的客户端对象
            this.stompClient = Stomp.over(this.socket);
            // 定义客户端的认证信息,按需求配置
            let headers = {
                Authorization: 'Bearer ' + localStorage.getItem('token'),
                'Access-Control-Allow-Origin': '*'
            };
            console.log(localStorage.getItem('token'));
            // 向服务器发起websocket连接
            console.log("监听接口");
            console.log('/topic/'+localStorage.getItem('uid'));
            this.stompClient.connect(headers, () => {
                this.stompClient.subscribe('/topic/'+localStorage.getItem('uid'), function(response) {
                    console.log('获得监听消息');
                    let v = JSON.parse(response.body);
                    console.log(v);
                    that.addTab(v)
                    that.chat_data.push(v);
                    // this.chat_data.push(v);
                    // this.addData(v);
                });
            }, (err) => {
                // 连接发生错误时的处理函数
                console.log('失败');
                console.log(err);
            });
        },    //连接 后台
        disconnect() {
            if (this.stompClient) {
                this.stompClient.disconnect();
            }
        },  // 断开连接
        addTab(chatInfo) {
            if (this.tabsItem.find(item => item.chat_id === chatInfo.chat_id)) {
                console.log('already exist');
            } else {
                // console.log("not find")
                // console.log(this.tabsItem)
                this.tabIndex++;
                this.tabsItem.push({
                    title: chatInfo.name,
                    chat_id: chatInfo.chat_id,
                    closable: false,
                    ref: 'ref',
                    content: ChatRoom
                });
                this.tabsPath.push({
                    chat_id: chatInfo.chat_id,
                    path: '/chatroom',
                    path_name: 'chatroom'
                });
                // console.log(this.tabsItem)
            }
        },
        removeTab(targetName) { //删除Tab
            let tabs = this.tabsItem; //当前显示的tab数组
            let activeName = this.activeTab; //点前活跃的tab

            //如果当前tab正活跃 被删除时执行
            if (activeName === targetName) {
                tabs.forEach((tab, index) => {
                    if (tab.name === targetName) {
                        let nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) {
                            activeName = nextTab.name;
                            this.tabClick(nextTab);
                        }
                    }
                });
            }
            this.activeTab = activeName;
            this.tabsItem = tabs.filter(tab => tab.name !== targetName);
            //在tabsPath中删除当前被删除tab的path
            this.tabsPath = this.tabsPath.filter(item => item.name !== targetName);
        },
        // tabClick(thisTab) {
        //     /*
        //     * thisTab:当前选中的tabs的实例
        //     * 通过当前选中tabs的实例获得当前实例的path 重新定位路由
        //     * */
        //     // console.log(this.$route.path)
        //     // let val = this.tabsPath.filter(item => thisTab.name === item.name)
        //     // this.$router.push({
        //     //   // path: val[0].path,
        //     //   name: val[0].path_name,
        //     //   query: {
        //     //     id:val[0].name
        //     //   }
        //     // })
        //     let i = this.tabsItem.find(item => item.name === thisTab.name);
        //     // i.content.id = thisTab.path_name;
        // }
    },
    sockets: {
        connect() {
            // this.id = this.socket.id;
            this.socket.emit('login', 'asdfg');    //监听connect事件
        },
        message(data) {  //监听message事件，方法是后台定义和提供的
            console.log(data);
        }
    },
    async mounted() {
        // const {data: res} = await this.$http.post(axios.defaults.baseURL + 'auth/register', {uid: sessionStorage.getItem('uid')})
        // this.$socket_path = sessionStorage.getItem('uid');
        console.log('开始初始化');
        await this.initWebSocket();
        console.log('初始化完成');
    },
    created() {
        // let x = {
        //     name: 'aasdfg',
        //     chat_id: 3
        // };
        // this.addTab(x);
        // this.room_info = this.$route.query.room_info;
        console.log("进入聊天窗口的room_info");
        console.log(this.room_info);
        this.tabsItem=[];
        this.tabsPath=[];
        let add_tabItem={
            title: "主世界",
            chat_id: this.room_info.chatId,
            closable: false,
            ref: 'tabs',
            content: ChatRoom
        };
        let add_tabsPath={
            chat_id: this.room_info.chatId,
            path: '/chatroom',
            path_name: 'chatroom'
        };
        this.tabsItem.push(add_tabItem);
        this.tabsPath.push(add_tabsPath);
        // //获得历史消息
        // let f={
        //   uid:sessionStorage.getItem('uid'),
        //   limit:100
        // }
        // this.$http.post(axios.defaults.baseURL + '', f).then((res) => {
        //   if(res.code==='000000'){
        //
        //   }else{
        //     this.$message.error(res.desc);
        //   }
        // })
    },
    components: {
        ChatRoom
    },
    beforeDestroy: function() {
        // 页面离开时断开连接,清除定时器
        this.disconnect();
        clearInterval(this.timer);
    }
};
</script>

<style scoped>

.el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
    height: 100%;
}

.el-menu--collapse {
    height: 100%;
}

.el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
}

.el-aside {
    color: #333;
}

.word{
    background-color:#eef1f6;
}

.el-submenu [class^=fa] {
    vertical-align: middle;
    margin-right: 5px;
    width: 24px;
    text-align: center;
    font-size: 16px;
}

</style>
